package com.coffee.admin.service.supplier.impl;

import com.alibaba.fastjson.JSONObject;
import com.coffee.admin.api.common.service.SmsCodeService;
import com.coffee.admin.api.platform.query.PlatformQuery;
import com.coffee.admin.api.platform.rep.PlatformOperateRes;
import com.coffee.admin.api.platform.result.PlatformResult;
import com.coffee.admin.api.supplier.query.SupplierQuery;
import com.coffee.admin.api.supplier.rep.SupplierDetailRep;
import com.coffee.admin.api.supplier.rep.SupplierListRep;
import com.coffee.admin.api.supplier.rep.SupplierOperateRes;
import com.coffee.admin.api.supplier.req.*;
import com.coffee.admin.api.supplier.result.SupplierResult;
import com.coffee.admin.api.supplier.service.SupplierService;
import com.coffee.admin.service.platform.bean.Platform;
import com.coffee.admin.service.platform.impl.PlatformServiceImpl;
import com.coffee.admin.service.supplier.bean.Supplier;
import com.coffee.admin.service.supplier.bean.SupplierRoleRelation;
import com.coffee.admin.service.supplier.dao.SupplierDao;
import com.coffee.admin.service.supplier.dao.SupplierRoleRelationDao;
import com.coffee.core.entity.Page;
import com.coffee.core.entity.PagerInfo;
import com.coffee.core.enums.ExceptionEnum;
import com.coffee.core.enums.SmsSourceEnum;
import com.coffee.core.exception.BusinessException;
import com.coffee.core.exception.ValidateBusinessException;
import com.coffee.core.util.*;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.util.*;


@DubboService(dynamic = true)
public class SupplierServiceImpl implements SupplierService {
    private static final Logger logger = LoggerFactory.getLogger(SupplierServiceImpl.class);

    @Resource
    private SupplierDao supplierDao;
    @Resource
    private SupplierRoleRelationDao supplierRoleRelationDao;
    @DubboReference
    private SmsCodeService smsCodeService;

    @Override
    public Page<SupplierListRep> getPager(SupplierListReq req, PagerInfo pr) {
        SupplierQuery supplierQuery = new SupplierQuery();
        BeanUtilExt.copyProperties(supplierQuery, req);
        supplierQuery.setPid(0);
        Page<SupplierListRep> pager = new Page<SupplierListRep>(pr.getStart(), pr.getPageSize());
        Integer count = supplierDao.countByAdmin(supplierQuery);
        pager.setTotalPage(count);
        if (count > 0) {
            List<SupplierListRep> supplierListReps = supplierDao.pageByAdmin(supplierQuery, pr.getStart(), pr.getPageSize());
            pager.setData(supplierListReps);
        }
        return pager;
    }

    @Override
    public Integer count(SupplierQuery param) {
        Integer count = supplierDao.count(param);
        return count;
    }

    @Override
    public SupplierResult getDetail(Integer id) {
        Supplier item = supplierDao.findById(id);
        if (item == null) {
            return null;
        }
        SupplierResult result = new SupplierResult();
        BeanUtilExt.copyProperties(result, item);

        return result;
    }

    @Override
    public SupplierDetailRep platformGetDetail(Integer id) {
        Supplier item = supplierDao.findById(id);
        if (item == null) {
            return null;
        }
        SupplierDetailRep result = new SupplierDetailRep();
        BeanUtilExt.copyProperties(result, item);

        return result;
    }

    @Override
    public List<SupplierResult> getList(SupplierQuery param, PagerInfo pr) {
        List<Supplier> list = supplierDao.page(param, pr.getStart(), pr.getPageSize());
        return DTOUtils.convertList(list, SupplierResult.class);
    }

    @Override
    public List<SupplierResult> getList(SupplierQuery param) {
        List<Supplier> list = supplierDao.page(param, 0, Integer.MAX_VALUE);
        return DTOUtils.convertList(list, SupplierResult.class);
    }

    @Override
    public List<SupplierResult> getList() {
        SupplierQuery param = new SupplierQuery();
        List<Supplier> list = supplierDao.page(param, 0, Integer.MAX_VALUE);
        return DTOUtils.convertList(list, SupplierResult.class);
    }


    @Override
    public void delete(Integer id) {
        supplierDao.deleteById(id);
    }

    @Override
    public void add(SupplierResult result) throws BusinessException {
        SupplierQuery supplierQuery=new SupplierQuery();
        supplierQuery.setMobile(result.getMobile());
        Supplier supplier = supplierDao.findFirst(supplierQuery);
        if (supplier!=null){
            throw BusinessException.build(ExceptionEnum.ERROR_1510);
        }
        Supplier item = new Supplier();
        BeanUtilExt.copyProperties(item, result);
        item.setCreateTime(new Date());
        item.setPid(0);
        supplierDao.insert(item);
    }

    @Override
    public Map<Integer, SupplierResult> getItemMap(Set<Integer> idSet) {
        Map<Integer, SupplierResult> map = new HashMap<Integer, SupplierResult>();
        List<Supplier> list = supplierDao.findByIds(StringUtil.setToList(idSet));
        List<SupplierResult> resultList = DTOUtils.convertList(list, SupplierResult.class);
        for (SupplierResult item : resultList) {
            map.put(item.getId(), item);
        }
        return map;
    }

    @Override
    public Map<Integer, SupplierResult> getItemMap() {
        Map<Integer, SupplierResult> map = new HashMap<Integer, SupplierResult>();
        SupplierQuery param = new SupplierQuery();
        List<Supplier> list = supplierDao.page(param, 0, Integer.MAX_VALUE);
        List<SupplierResult> resultList = DTOUtils.convertList(list, SupplierResult.class);
        for (SupplierResult item : resultList) {
            map.put(item.getId(), item);
        }
        return map;
    }

    @Override
    public void updateIsEnable(SupplierUpdateIsEnableReq req) throws BusinessException {
        Supplier item = new Supplier();
        item.setId(req.getId());
        item.setIsEnable(req.getIsEnable());
        supplierDao.updateById(item);
    }

    @Override
    public void updateMobile(SupplierUpdateMobileReq req) throws BusinessException {
        SupplierQuery param = new SupplierQuery();
        param.setMobile(req.getMobile());
        Supplier supplier = supplierDao.findFirst(param);
        if (supplier != null) {
            throw new BusinessException(ExceptionEnum.ERROR_1500.getCode(), ExceptionEnum.ERROR_1500.getMessage());
        }
        Supplier item = new Supplier();
        BeanUtilExt.copyProperties(item, req);
        supplierDao.updateById(item);
    }

    @Override
    public void updatePassword(SupplierUpdatePasswordReq req) throws BusinessException {
        Supplier supplier = supplierDao.findById(req.getId());
        if (supplier == null) {
            throw BusinessException.build(ExceptionEnum.ERROR_1500);
        }
        if (PasswordUtil.checkPass(req.getNewPassword(), supplier.getPassword())) {
            throw BusinessException.build(ExceptionEnum.ERROR_1501);
        }
        Supplier item = new Supplier();
        item.setId(req.getId());
        item.setPassword(PasswordUtil.getPass(req.getNewPassword()));
        supplierDao.updateById(item);
    }

    public void checkMobile(String mobile) throws BusinessException {
        ValidateBusinessException.assertStringNotBlank(mobile, ExceptionEnum.ERROR_1201);
        boolean isMobile = RegexUtils.checkMobile(mobile);
        ValidateBusinessException.assertTrue(isMobile, ExceptionEnum.ERROR_1218);
    }


    @Override
    public void updateBuyPermission(SupplierUpdateBuyPermissionReq req) throws BusinessException {
        Supplier item = new Supplier();
        if (StringUtils.isNotEmpty(req.getMobile())) {
            SupplierQuery param = new SupplierQuery();
            param.setMobile(req.getMobile());
            Supplier supplier = supplierDao.findFirst(param);
            if (supplier != null) {
                throw new BusinessException(ExceptionEnum.ERROR_1500.getCode(), ExceptionEnum.ERROR_1500.getMessage());
            }
            item.setMobile(req.getMobile());
        }
        item.setName(req.getName());
        item.setId(req.getId());
        item.setSalePermission(req.getSalePermission());
        item.setBusinessCode(req.getBusinessCode());
        item.setBusinessName(req.getBusinessName());
        supplierDao.updateById(item);
    }

    @Override
    public Page<SupplierOperateRes> findMerchantOperatorListByPage(SupplierAccountListReq params, PagerInfo pagerInfo) throws BusinessException {
        Page<SupplierOperateRes> pageData = new Page<>(pagerInfo.getPageIndex(), pagerInfo.getPageSize());
        SupplierQuery supplierQuery = new SupplierQuery();
        BeanUtilExt.copyProperties(supplierQuery, params);
        supplierQuery.setPid(params.getSupplierId());
        int amount = this.supplierDao.count(supplierQuery);
        if (amount > 0) {
            List<SupplierOperateRes> supplierOperateRes = supplierDao.pageByPlatformOperateRes(supplierQuery, pagerInfo.getPageIndex(), pagerInfo.getPageSize());
            pageData.setData(supplierOperateRes);
        }
        pageData.setAmount(amount);
        return pageData;
    }

    @Override
    public SupplierOperateRes findMerchantOperatorDetail(SupplierAccountListReq params) {
        SupplierQuery supplierQuery = new SupplierQuery();
        BeanUtilExt.copyProperties(supplierQuery, params);
        supplierQuery.setId(params.getId());
        SupplierOperateRes merchantOperatorDetail = supplierDao.findMerchantOperatorDetail(supplierQuery);
        return merchantOperatorDetail;
    }

    @Override
    public SupplierResult getSupplierResult(SupplierQuery param) throws BusinessException {
        SupplierResult supplierResult = new SupplierResult();
        Supplier supplier = supplierDao.findFirst(param);
        if (supplier == null) {
            return null;
        }
        BeanUtilExt.copyProperties(supplierResult, supplier);
        return supplierResult;
    }

    @Override
    public void insertSupplierOperate(SupplierAccountAddReq params) throws BusinessException {
        logger.info("insertSupplierOperate=" + JSONObject.toJSONString(params));
        ValidateBusinessException.assertStringNotBlank(params.getName(), ExceptionEnum.ERROR_1506);
        ValidateBusinessException.assertStringNotBlank(params.getMobile(), ExceptionEnum.ERROR_1507);
        List<Integer> roleIdList = params.getRoleIdList();
        ValidateBusinessException.assertCollectionNotEmpty(roleIdList, ExceptionEnum.ERROR_1508);
        ValidateBusinessException.assertStringNotBlank(params.getPassword(), ExceptionEnum.ERROR_1509);

        SupplierQuery query = new SupplierQuery();
        query.setMobile(params.getMobile());
        Supplier supplier = supplierDao.findFirst(query);
        Integer operatorId = null;
        if (supplier != null) {
            throw new BusinessException(ExceptionEnum.ERROR_1510.getCode(), ExceptionEnum.ERROR_1510.getMessage());
        }
        supplier = new Supplier();
        BeanUtilExt.copyProperties(supplier, params);
        supplier.setCreateTime(new Date());
        supplier.setPassword(PasswordUtil.getPass(params.getPassword()));
        // 添加后默认为可用
        supplier.setIsEnable("Y");
        supplier.setPid(params.getSupplierId());
        logger.info("insertSupplierOperate(添加账户)" + JSONObject.toJSONString(supplier));
        this.supplierDao.insert(supplier);
        operatorId = supplier.getId();
        logger.info("insertEpMerchantOperator(添加账户角色关联表):operatorId=" + operatorId + ",roleIdList=" + JSONObject.toJSONString(roleIdList));
        supplierRoleRelationDao.insertBatch(operatorId, roleIdList);
    }


    @Override
    public void updateSupplierOperate(SupplierAccountUpdateReq params) throws BusinessException {
        List<Integer> roleIdList = params.getRoleIdList();
        Supplier supplier = this.supplierDao.findById(params.getId());
        ValidateBusinessException.assertNonNull(supplier, ExceptionEnum.ERROR_1511);
        Integer operatorId = supplier.getId();
        ValidateBusinessException.assertFalse("Y".equals(supplier.getIsAdmin()), ExceptionEnum.ERROR_1512);
        Supplier updateSupplier = new Supplier();
        BeanUtilExt.copyProperties(updateSupplier, params);
        logger.info("updateSupplierOperate(修改账户信息):" + JSONObject.toJSONString(updateSupplier));
        supplierDao.updateById(updateSupplier);
        if (roleIdList != null && roleIdList.size() > 0) {
            //删除账户角色关联表
            logger.info("updateSupplierOperate(删除账户角色关联表):operatorId=" + operatorId);
            supplierRoleRelationDao.deleteBySupplierIdId(operatorId);
            logger.info("updateSupplierOperate(添加账户角色关联表):", "operatorId=" + operatorId + ",roleIdList=" + JSONObject.toJSONString(roleIdList));
            supplierRoleRelationDao.insertBatch(operatorId, roleIdList);
        }
    }

    @Override
    public void updateRemark(SupplierAccountUpdateReq params) throws BusinessException {
        Supplier supplier = this.supplierDao.findById(params.getId());
        ValidateBusinessException.assertNonNull(supplier, ExceptionEnum.ERROR_1511);
        ValidateBusinessException.assertFalse("Y".equals(supplier.getIsAdmin()), ExceptionEnum.ERROR_1512);
        Supplier updateSupplier = new Supplier();
        BeanUtilExt.copyProperties(updateSupplier, params);
        logger.info("updateSupplierOperate(修改账户信息):" + JSONObject.toJSONString(updateSupplier));
        supplierDao.updateById(updateSupplier);
    }

}
